import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useUserStore } from '@/stores'
import { addCartListAPI, getCartListAPI, deleteCartListAPI } from '@/apis/cart'
import { ElMessage } from 'element-plus';

export const useCartStore = defineStore('cart', () => {
  // state - 购物车列表数据
  const cartList = ref(JSON.parse(localStorage.getItem('cart')) || [])

  // getters - 转换为计算属性
  const allCount = computed(() => {
    return cartList.value.reduce((pre, item) => pre + item.count, 0)
  })

  const allPrice = computed(() => {
    return cartList.value.reduce((pre, item) => pre + item.count * item.price, 0)
  })

  // 已选商品数量
  const selectedCount = computed(() => {
    return cartList.value.reduce(
      (pre, item) => pre + (item.selected ? item.count : 0),
      0
    )
  })

  // 已选商品总价
  const selectedPrice = computed(() => {
    return cartList.value.reduce(
      (pre, item) => pre + (item.selected ? item.count * item.price : 0),
      0
    )
  })

  const isLogin = computed(() => {
    const userStore = useUserStore()
    return Boolean(userStore.userInfo?.token)
  })

  // 是否全选
  const isAll = computed(() => {
    return cartList.value.length > 0 && cartList.value.every(item => item.selected)
  })

  // 修改商品数量
  const changeCount = async (skuId, count) => {
    if (isLogin.value) {
      try {
        // 登录状态下，先更新服务器数据
        await addCartListAPI({
          skuId,
          count
        })
        // 然后更新本地购物车列表
        await updateCartList()
      } catch (error) {
        console.error('修改商品数量失败:', error)
        ElMessage.error('修改商品数量失败，请稍后重试')
        throw error
      }
    } else {
      // 未登录状态，只更新本地数据
      const item = cartList.value.find(item => item.skuId === skuId)
      if (item) {
        item.count = count
        localStorage.setItem('cart', JSON.stringify(cartList.value))
      }
    }
  }

  // 单选商品
  const singleCheck = (skuId, selected) => {
    const item = cartList.value.find(item => item.skuId === skuId)
    if (item) {
      item.selected = selected
      localStorage.setItem('cart', JSON.stringify(cartList.value))
    }
  }

  // 获取最新的购物车列表
  const updateCartList = async () => {
    if (isLogin.value) {
      try {
        const res = await getCartListAPI()
        console.log('从服务器获取的购物车列表:', res.result)
        cartList.value = res.result
        localStorage.setItem('cart', JSON.stringify(cartList.value)) // 同步到本地存储
      } catch (error) {
        console.error('获取购物车列表失败:', error)
        throw error
      }
    }
  }

  // actions - 转换为普通函数
  const addCart = async (goods) => {
    try {
      // 已登录状态，直接与服务器同步
      if (isLogin.value) {
        const res = await addCartListAPI({
          skuId: goods.skuId,
          count: goods.count
        })
        
        if (res.code === 200) {
          ElMessage.success('商品已添加到购物车')
          await updateCartList() // 更新购物车列表
        } else if (res.code === 400) {
          ElMessage.error(res.message)
          return // 提前返回避免执行后续代码
        }
      } else {
        // 未登录状态，更新本地数据
        const existItem = cartList.value.find(
          item =>
            item.skuId === goods.skuId &&
            item.attrsText === goods.attrsText
        )

        if (existItem) {
          existItem.count += goods.count
        } else {
          cartList.value.unshift(goods)
        }

        // 本地存储
        localStorage.setItem('cart', JSON.stringify(cartList.value))
      }
    } catch (error) {
      console.error('添加购物车失败:', error)
      // 仅显示非库存不足的错误提示
      if (!error.message.includes('库存不足')) {
        ElMessage.error('添加购物车失败，请稍后重试')
      }
      throw error
    }
  }

  // 删除购物车商品
  const deleteCart = async (skuId) => {
    if (isLogin.value) {
      try {
        await deleteCartListAPI([skuId])
        await updateCartList()
        console.log('商品已从服务器购物车中删除')
      } catch (error) {
        console.error('删除购物车商品失败:', error)
        throw error
      }
    } else {
      // 未登录时只更新本地数据
      cartList.value = cartList.value.filter(item => item.skuId !== skuId)
      localStorage.setItem('cart', JSON.stringify(cartList.value))
      console.log('商品已从本地购物车中删除')
    }
  }

  // 清空本地购物车
  const clearCart = () => {
    cartList.value = []
    localStorage.setItem('cart', JSON.stringify([]))
  }

  return {
    cartList,
    allCount,
    allPrice,
    selectedCount,
    selectedPrice,
    isAll,
    addCart,
    deleteCart,
    clearCart,
    updateCartList,
    changeCount,
    singleCheck
  }
})